<template>
  <div class="settings-container">
    <div class="settings-header">
      <h1>设置</h1>
    </div>

    <div class="settings-content">
      <div class="settings-sidebar">
        <div 
          v-for="section in sections" 
          :key="section.id"
          class="section-item"
          :class="{ active: currentSection === section.id }"
          @click="currentSection = section.id"
        >
          <i :class="section.icon"></i>
          <span>{{ section.name }}</span>
        </div>
      </div>

      <div class="settings-main">
        <!-- 个人资料设置 -->
        <div v-if="currentSection === 'profile'" class="settings-section">
          <h2>个人资料</h2>
          <div class="profile-settings">
            <div class="avatar-upload-block">
              <label class="avatar-label">* 套餐图片:</label>
              <el-upload
                class="avatar-uploader"
                action="/api/user/common/upload"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :auto-upload="true"
                name="file"
                :headers="uploadHeaders"
              >
                <div class="avatar-upload-box">
                  <template v-if="avatarUrl">
                    <img :src="avatarUrl" class="avatar-preview" />
                  </template>
                  <template v-else>
                    <i class="el-icon-upload avatar-upload-icon"></i>
                    <div class="avatar-upload-text">上传图片</div>
                  </template>
                </div>
              </el-upload>
              <div class="avatar-upload-tips">
                <div>图片大小不超过2M</div>
                <div>仅能上传 PNG JPEG JPG类型图片</div>
                <div>建议上传200*200或300*300尺寸的图片</div>
              </div>
            </div>

            <div class="form-group">
              <label>昵称</label>
              <input 
                type="text" 
                v-model="userProfile.nickname"
                placeholder="请输入昵称"
              >
            </div>

            <div class="form-group">
              <label>个性签名</label>
              <textarea 
                v-model="userProfile.bio"
                placeholder="介绍一下自己吧"
                rows="3"
              ></textarea>
            </div>

            <div class="form-group">
              <label>性别</label>
              <div class="radio-group">
                <label class="radio-label">
                  <input 
                    type="radio" 
                    v-model="userProfile.gender" 
                    value="male"
                  >
                  男
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    v-model="userProfile.gender" 
                    value="female"
                  >
                  女
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    v-model="userProfile.gender" 
                    value="other"
                  >
                  保密
                </label>
              </div>
            </div>

            <div class="form-group">
              <label>生日</label>
              <input 
                type="date" 
                v-model="userProfile.birthday"
              >
            </div>
            <div class="form-actions">
              <el-button type="primary" @click="submitProfile">确定修改</el-button>
            </div>
          </div>
        </div>

        <!-- 账号安全设置 -->
        <div v-if="currentSection === 'security'" class="settings-section">
          <h2>账号安全</h2>
          <div class="security-settings">
            <div class="security-item">
              <div class="security-info">
                <h3>修改密码</h3>
                <p>定期修改密码可以提高账号安全性</p>
              </div>
              <button class="action-btn" @click="showChangePassword = true">
                修改
              </button>
            </div>

            <div class="security-item">
              <div class="security-info">
                <h3>绑定手机</h3>
                <p>已绑定：{{ userProfile.phone }}</p>
              </div>
              <button class="action-btn" @click="showChangePhone = true">
                修改
              </button>
            </div>

            <div class="security-item">
              <div class="security-info">
                <h3>绑定邮箱</h3>
                <p>已绑定：{{ userProfile.email }}</p>
              </div>
              <button class="action-btn" @click="showChangeEmail = true">
                修改
              </button>
            </div>

            <div class="security-item">
              <div class="security-info">
                <h3>两步验证</h3>
                <p>开启后登录需要验证码</p>
              </div>
              <div class="toggle-switch">
                <input 
                  type="checkbox" 
                  :id="'twoFactor'" 
                  v-model="userProfile.twoFactorEnabled"
                >
                <label :for="'twoFactor'"></label>
              </div>
            </div>
          </div>
        </div>

        <!-- 隐私设置 -->
        <div v-if="currentSection === 'privacy'" class="settings-section">
          <h2>隐私设置</h2>
          <div class="privacy-settings">
            <div class="privacy-item">
              <div class="privacy-info">
                <h3>个人资料可见性</h3>
                <p>控制谁可以看到你的个人资料</p>
              </div>
              <select v-model="userProfile.profileVisibility">
                <option value="public">所有人</option>
                <option value="friends">仅好友</option>
                <option value="private">仅自己</option>
              </select>
            </div>

            <div class="privacy-item">
              <div class="privacy-info">
                <h3>在线状态</h3>
                <p>是否显示你的在线状态</p>
              </div>
              <div class="toggle-switch">
                <input 
                  type="checkbox" 
                  :id="'onlineStatus'" 
                  v-model="userProfile.showOnlineStatus"
                >
                <label :for="'onlineStatus'"></label>
              </div>
            </div>

            <div class="privacy-item">
              <div class="privacy-info">
                <h3>消息通知</h3>
                <p>接收新消息通知</p>
              </div>
              <div class="toggle-switch">
                <input 
                  type="checkbox" 
                  :id="'messageNotification'" 
                  v-model="userProfile.messageNotification"
                >
                <label :for="'messageNotification'"></label>
              </div>
            </div>
          </div>
        </div>

        <!-- 通知设置 -->
        <div v-if="currentSection === 'notifications'" class="settings-section">
          <h2>通知设置</h2>
          <div class="notification-settings">
            <div class="notification-item">
              <div class="notification-info">
                <h3>系统通知</h3>
                <p>接收系统更新和维护通知</p>
              </div>
              <div class="toggle-switch">
                <input 
                  type="checkbox" 
                  :id="'systemNotification'" 
                  v-model="userProfile.systemNotification"
                >
                <label :for="'systemNotification'"></label>
              </div>
            </div>

            <div class="notification-item">
              <div class="notification-info">
                <h3>活动通知</h3>
                <p>接收游戏活动和更新通知</p>
              </div>
              <div class="toggle-switch">
                <input 
                  type="checkbox" 
                  :id="'activityNotification'" 
                  v-model="userProfile.activityNotification"
                >
                <label :for="'activityNotification'"></label>
              </div>
            </div>

            <div class="notification-item">
              <div class="notification-info">
                <h3>评论通知</h3>
                <p>接收评论和回复通知</p>
              </div>
              <div class="toggle-switch">
                <input 
                  type="checkbox" 
                  :id="'commentNotification'" 
                  v-model="userProfile.commentNotification"
                >
                <label :for="'commentNotification'"></label>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <div v-if="showChangePassword" class="modal">
      <div class="modal-content">
        <h3>修改密码</h3>
        <div class="form-group">
          <label>当前密码</label>
          <input type="password" v-model="passwordForm.currentPassword">
        </div>
        <div class="form-group">
          <label>新密码</label>
          <input type="password" v-model="passwordForm.newPassword">
        </div>
        <div class="form-group">
          <label>确认新密码</label>
          <input type="password" v-model="passwordForm.confirmPassword">
        </div>
        <div class="modal-actions">
          <button class="cancel-btn" @click="showChangePassword = false">取消</button>
          <button class="confirm-btn" @click="changePassword">确认</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import store from '@/store'

const currentSection = ref('profile')
const showChangePassword = ref(false)
const showChangePhone = ref(false)
const showChangeEmail = ref(false)

const sections = [
  { id: 'profile', name: '个人资料', icon: 'fas fa-user' },
  { id: 'security', name: '账号安全', icon: 'fas fa-shield-alt' },
  { id: 'privacy', name: '隐私设置', icon: 'fas fa-lock' },
  { id: 'notifications', name: '通知设置', icon: 'fas fa-bell' }
]

const userProfile = reactive({
  id: 0,
  avatar: '/avatars/default.jpg',
  nickname: '用户昵称',
  bio: '这是个性签名',
  gender: 'other',
  birthday: '2000-01-01',
  phone: '138****8888',
  email: 'user@example.com',
  twoFactorEnabled: false,
  profileVisibility: 'public',
  showOnlineStatus: true,
  messageNotification: true,
  systemNotification: true,
  activityNotification: true,
  commentNotification: true
})

const avatarUrl = ref('')

const uploadHeaders = computed(() => ({
  token: getToken() || ''
}))

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('只能上传 PNG/JPEG/JPG 格式图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response: any) => {
  // response.data 为图片地址
  avatarUrl.value = response.data
  userProfile.avatar = response.data
}

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const changePassword = () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    alert('两次输入的密码不一致')
    return
  }
  // 实现修改密码逻辑
  showChangePassword.value = false
}

const submitProfile = async () => {
  try {
    // 组装 userDTO（不传id）
    const userDTO = {
      name: userProfile.nickname,
      signature: userProfile.bio,
      sex: userProfile.gender,
      birthday: userProfile.birthday,
      image: userProfile.avatar // 新增头像字段
    }
    await request.put('/user/user/settings', userDTO)
    
    // 获取最新的用户信息
    const userDetailResponse = await request.get('/user/user/detail')
    const updatedUserInfo = {
      id: userDetailResponse.data.id,
      username: userDetailResponse.data.username,
      avatar: userDetailResponse.data.image,
      email: userDetailResponse.data.email,
      phone: userDetailResponse.data.phone
    }
    
    // 更新 Vuex store 中的用户信息
    store.dispatch('login', updatedUserInfo)
    
    ElMessage.success('修改成功')
  } catch (e) {
    ElMessage.error('修改失败')
  }
}

onMounted(async () => {
  try {
    const res = await request.get('/user/user/detail')
    userProfile.nickname = res.data.username || ''
    userProfile.bio = res.data.signature || ''
    userProfile.gender = res.data.sex || 'other'
    userProfile.birthday = res.data.birthday || ''
    userProfile.avatar = res.data.image || '/avatars/default.jpg'
    userProfile.phone = res.data.phone || ''
    userProfile.email = res.data.email || ''
    avatarUrl.value = res.data.image || '/avatars/default.jpg'
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  }
})
</script>

<style scoped>
.settings-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.settings-header {
  margin-bottom: 2rem;
}

.settings-header h1 {
  margin: 0;
  color: #2c3e50;
}

.settings-content {
  display: flex;
  gap: 2rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.settings-sidebar {
  width: 200px;
  border-right: 1px solid #eee;
  padding: 1rem 0;
}

.section-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  cursor: pointer;
  color: #666;
  transition: all 0.3s;
}

.section-item:hover {
  background: #f5f5f5;
}

.section-item.active {
  background: #f0f9f4;
  color: #42b983;
}

.section-item i {
  width: 20px;
  text-align: center;
}

.settings-main {
  flex: 1;
  padding: 2rem;
}

.settings-section h2 {
  margin: 0 0 2rem;
  color: #2c3e50;
}

.profile-settings {
  max-width: 600px;
}

.avatar-upload-block {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 2rem;
}

.avatar-label {
  color: #333;
  font-size: 18px;
  margin-bottom: 8px;
  min-width: 100px;
  text-align: left;
  display: block;
}

.avatar-uploader {
  width: 320px;
  height: 320px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: block;
  background: #fafafa;
  transition: border-color 0.3s;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-upload-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #999;
}

.avatar-upload-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.avatar-upload-text {
  font-size: 18px;
  color: #333;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.avatar-upload-tips {
  margin-left: 32px;
  color: #666;
  font-size: 16px;
  line-height: 2;
  min-width: 320px;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #2c3e50;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.radio-group {
  display: flex;
  gap: 2rem;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  cursor: pointer;
}

.security-settings,
.privacy-settings,
.notification-settings {
  max-width: 600px;
}

.security-item,
.privacy-item,
.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 0;
  border-bottom: 1px solid #eee;
}

.security-info,
.privacy-info,
.notification-info {
  flex: 1;
}

.security-info h3,
.privacy-info h3,
.notification-info h3 {
  margin: 0 0 0.5rem;
  color: #2c3e50;
}

.security-info p,
.privacy-info p,
.notification-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.action-btn {
  padding: 0.5rem 1rem;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.toggle-switch {
  position: relative;
  width: 50px;
  height: 24px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-switch label {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 24px;
}

.toggle-switch label:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

.toggle-switch input:checked + label {
  background-color: #42b983;
}

.toggle-switch input:checked + label:before {
  transform: translateX(26px);
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  width: 400px;
}

.modal-content h3 {
  margin: 0 0 1.5rem;
  color: #2c3e50;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.cancel-btn {
  padding: 0.8rem 1.5rem;
  background: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  padding: 0.8rem 1.5rem;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.form-actions {
  margin-top: 2rem;
}
</style> 